﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Globalization;
using Microsoft.Practices.Unity;
using Web.SystemLogin.Services;
using Web.SystemLogin.Models;
using Web.SystemLogin.Business;
using System.Web.Security;
using Web.SystemLogin.ServiceContract;
using System.Data;
using DreamBuilder.Common;
using Common;
using DreamBuilder.Core.Container;
using DreamBuilder.Core.Log;
using CommonModule;
using Web.SystemConfig.Services;
using System.Collections;

namespace Web.Views.SystemLogin
{
    public partial class SystemLogin : PageBase
    {
        [Dependency]
        public ISystemLogin SystemLoginComponent
        {
            get;
            set;
        }

        [Dependency]
        public IAuth_User SystemConfigComponent
        {
            get;
            set;
        }

        //private ISystemLoginService _systemloginservice = ServiceProxyFactory.Create<ISystemLoginService>("systemloginservice");

        /// <summary>
        /// page load funtion
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            this.DBHelpName = DBHelperString.Dictionary;
            if (!Page.IsPostBack)
            {
                //清除session
                Session.Clear();
                //注入脚本，使得顶级window对象转向登陆页。
                this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "redirectLocation();", true);
            }
            Page.DataBind();
        }


        #region Web 窗体设计器生成的代码
        /// <summary>
        /// 
        /// </summary>

        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// 设计器支持所需的方法 - 不要使用代码编辑器修改
        /// 此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.ImageButton1.ServerClick += new EventHandler(ImageButton1_Click);

        }
        #endregion

        private void ImageButton1_Click(object sender, EventArgs e)
        {
            //验证 add by lyn20111230
            bool isOK = false;
            try
            {
                //验证当前业务系统的用户
                string userID = string.Empty;
                string loginName = this.txtUserID.Value.Trim();
                string passwdNoEncry = this.txtPasswd.Value.Trim();
                string passwd = EncryptDecrypt.EncryptPassword(this.txtPasswd.Value.Trim(), "MD5");
                userID = SystemLoginComponent.CheckCNPCLoginNameAvailable(loginName); 
                //AD验证(暂时先去掉)
                //bool adOk = SystemLoginComponent.ValidateUser("cnpc.com.cn", loginName,passwdNoEncry, "cnpc");
                bool adOK = false;
                if (!adOK)
                {
                    //数据库验证UP
                    isOK = SystemLoginComponent.ValiadateUserPWD(loginName, passwd, "UserPwd");
                }
                else
                {
                    //数据库验证AD
                    isOK = SystemLoginComponent.ValiadateUserPWD(loginName, passwd, "AD");                  
                }

                if (isOK)
                {
                    //login in suc
                    //create the currentuser session
                    //传人真正的 userID
                    User currentUser = SystemLoginComponent.GetCurrentUser(userID);
                    Session["CurrentUser"] = currentUser;
                    Session["OALoginUserID"] = currentUser.User_ID;
                    //记录域密码
                    currentUser.Login_Pwd = this.txtPasswd.Value;
                    //更新用户的登录时间
                    SystemLoginComponent.UpdateUserLoginInfo(userID); 

                    OnlineUser ou = new OnlineUser();

                    #region 记录登录日志
                    ILogger log = UContainer.Resolve<ILogger>(Category.LoginLog);
                    string errMsg = String.Empty;
                    string macAdress = GetUserMacSrc(out errMsg);

                    log.Info(ou.GetLogInfo(currentUser.User_ID, currentUser.User_Name, Request.UserHostAddress, macAdress, Thread.CurrentThread.CurrentUICulture.Name, Request.Browser.Type));
                    #endregion

                    ou.CheckUserOnLine(
                        currentUser.SessionID, currentUser.User_ID, currentUser.Real_ID,currentUser.User_Name, currentUser.Login_ID, currentUser.Last_Login_Time, currentUser.This_Login_Time, currentUser.ORG_ID);

                    if (Request.QueryString["ReturnUrl"] != null && Request.QueryString["ReturnUrl"].ToString().ToLower().IndexOf("default.aspx") == -1 && Request.QueryString["ReturnUrl"].ToString().ToLower().IndexOf("logout.aspx") == -1)
                    {
                        FormsAuthentication.RedirectFromLoginPage(userID, false);
                        //Response.Redirect("../../index.aspx"); 
                    }
                    else
                    {
                        FormsAuthentication.SetAuthCookie(userID, false);

                        //Modifid by lyn 将打开子页面修改成直接跳转到首页 20111230
                        Response.Redirect("../../index.aspx");            
                    }
                }
                else
                {
                    MessageShow.ShowMessageBox(this, GetString("InvalidUserOrPassword"));
                }

            }
            catch (System.Exception err)
            {
                string error = err.Message; 
                WriteErrorLog(error,OracleLogType.System);
                MessageShow.ShowMessageBox(this, GetString("UnkonwnError"));
            }
            finally
            {
                //将在线人数保存到Application对象中
                if (Session["CurrentUser"] != null)
                {
                    try
                    {
                        Web.SystemLogin.Models.User userSession = ((User)Session["CurrentUser"]);

                        Application.Lock();
                        Hashtable ht = (Hashtable)Application["User_Sission"];
                        //加入Application对象
                        ht.Add(Session.SessionID,userSession);
                        //存入数据库
                        if (!SystemConfigComponent.CheckUserStateExsist(userSession.User_ID))
                        {
                            SystemConfigComponent.AddUserToUserState(userSession.User_ID, userSession.Real_ID, Request.Browser.Platform, Request.UserHostAddress, Request.Browser.Type);
                        }
                        else
                        {
                            SystemConfigComponent.UpdateUserState(userSession.User_ID, userSession.Real_ID, Request.Browser.Platform, Request.UserHostAddress, Request.Browser.Type, true);
                        }
                        Application["User_Session"] = ht;
                    }
                    catch { }
                    finally
                    {
                        Application.UnLock();
                    }
                }
            }
        }
    }
}
